package model;

import toolkit.Debug;
import exception.DrawException;
import exception.GameException;
import exception.GameRoundEndException;

public class HoldEmGameRound extends GameRound
{
	protected final HoldEmTable table;
	
	protected HoldEmGameRoundState currentState;
	
	public HoldEmGameRound(HoldEmTable table)
	{
		super(table);
		
		this.table = table;
		
		table.clear();
		
		table.shiftPositions();
	}

	public HoldEmGameRoundState getCurrentState()
	{
		return currentState;
	}
	
	protected ChosenAction determineAction(int actionsPerformed, Participant participant, int highestStateBet)
	{
		ChosenAction chosenAction = null;
		
		HoldEmGame game = table.getGame();
		
		switch (game.getGameType())
		{
			// Sit and go.
			case SINGLE_TABLE:
				
				switch (currentState)
				{
					// In the pre flop the first two participants need to raise with the blinds.
					case PRE_FLOP:
						
						// 0 or 1
						if (actionsPerformed == 0)
						{
							chosenAction = new ChosenAction(Action.RAISE);
							
							chosenAction.setAmountRaised(game.getSmallBlind());
						}
						
						break;
				}
				
				break;
		}
		
		if (chosenAction != null)
		{
			chosenAction.isDeterminedByRules(true);
		}
		// If no action is chosen for the player by the game rules let the player decide.
		else
		{
			chosenAction = participant.chooseAction(highestStateBet);
		}
		
		return chosenAction;
	}
	
	public void dispatch() throws GameException
	{
		try
		{
			for (HoldEmGameRoundState gameRoundState: HoldEmGameRoundState.values())
			{
				currentState = gameRoundState;
				
				dispatchState(gameRoundState);
			}
		}
		catch (DrawException e)
		{
			throw new GameException("There are no more cards to draw.");
		}
		catch (GameRoundEndException e)
		{
			currentState = HoldEmGameRoundState.END;
			
			try
			{
				dispatchState(currentState);
			}
			catch (Exception e1)
			{
				System.err.println(e1.getStackTrace());
				
				Debug.log(e1);
			}
		}
	}
	
	public void dispatchState(HoldEmGameRoundState gameRoundState) throws DrawException, GameRoundEndException
	{
		switch (gameRoundState)
		{
			case START:
				
				drawHandCards(2);
				
				break;
			
			case PRE_FLOP:
				
				chooseAction();
				
				break;
			
			case FLOP:
				
				drawBoardCards(3);
				
				chooseAction();
				
				break;
				
			case TURN:
				
				drawBoardCard();
				
				chooseAction();
				
				break;
			
			case RIVER:
				
				drawBoardCard();
				
				chooseAction();
				
				break;
			
			case END:
				
				showHandCards();
				
				payout();

				/*for (Participant p: table.getParticipants())
				{
					Debug.log(p, "participant");
					
					Debug.log(p.getLastCombination(), "combination");
					
					Debug.printSolidLine();
				}*/
				
				break;
		}
	}
}
